package com.example.kotlinExample.entity

import kotlin.math.abs

/**
 *
 *
 * @author liliang
 */
fun main() {

    val ps = arrayOf(Point(120.2043, 30.2795), Point(120.2030, 30.2511), Point(120.1810, 30.2543), Point(120.1798, 30.2781), Point(120.1926, 30.2752))
    val n1 = Point(120.1936, 30.2846)
    val n2 = Point(120.1823, 30.2863)
    val n3 = Point(120.2189, 30.2712)
    val y1 = Point(120.1902, 30.2712)
    val y2 = Point(120.1866, 30.2672)
    val y4 = Point(120.1869, 30.2718)

    println("n1:" + isPtInPoly(n1.x, n1.y, ps))
    println("n2:" + isPtInPoly(n2.x, n2.y, ps))
    println("n3:" + isPtInPoly(n3.x, n3.y, ps))
    println("y1:" + isPtInPoly(y1.x, y1.y, ps))
    println("y2:" + isPtInPoly(y2.x, y2.y, ps))
    println("y4:" + isPtInPoly(y4.x, y4.y, ps))
}

fun isPtInPoly(ALon: Double, ALat: Double, ps: Array<Point>): Boolean {
    var dLon1: Double
    var dLon2: Double
    var dLat1: Double
    var dLat2: Double
    var dLon: Double
    if (ps.size < 3) {
        return false
    }
    var iSum = 0
    val iCount: Int = ps.size
    var iIndex = 0
    while (iIndex < iCount) {
        if (iIndex == iCount - 1) {
            dLon1 = ps[iIndex].x
            dLat1 = ps[iIndex].y
            dLon2 = ps[0].x
            dLat2 = ps[0].y
        } else {
            dLon1 = ps[iIndex].x
            dLat1 = ps[iIndex].y
            dLon2 = ps[iIndex + 1].x
            dLat2 = ps[iIndex + 1].y
        }
        // 以下语句判断A点是否在边的两端点的水平平行线之间，在则可能有交点，开始判断交点是否在左射线上
        if (ALat >= dLat1 && ALat < dLat2 || ALat >= dLat2 && ALat < dLat1) {
            if (abs(dLat1 - dLat2) > 0) {
                //得到 A点向左射线与边的交点的x坐标：
                dLon = dLon1 - (dLon1 - dLon2) * (dLat1 - ALat) / (dLat1 - dLat2)
                // 如果交点在A点左侧（说明是做射线与 边的交点），则射线与边的全部交点数加一：
                if (dLon < ALon) {
                    iSum++
                }
            }
        }
        iIndex++
    }
    return iSum % 2 != 0
}
